"use client";

import {
  useState,
  Fragment,
  useRef,
  ChangeEventHandler,
  useLayoutEffect,
} from "react";
import * as _ from "lodash";
import { useColoContext } from "../context";

export default () => {
  // 全局颜色
  const { setColor } = useColoContext();

  // 输入的
  const [inputValue, setInputValue] = useState<string>("");
  // span的
  const [outputValue, setOutputValue] = useState<string>("");
  // span像素长度
  const [spanWidth, setSpanWidth] = useState<number>(0);
  // span实时改颜色并且不闪烁用（07:42:00）
  const spanRef = useRef<HTMLSpanElement | null>(null);


  /**
   * 判断首字母是否为英文
   * @param value string
   * @returns boolean
   */
  const startsWithNonNumeric = (value: string): boolean => {
    return value.length > 0 && isNaN(parseInt(value[0] ?? '', 10));
  };

  const handleInputChange: ChangeEventHandler<HTMLInputElement> = (event) => {
    const val = event.target.value;
    setInputValue(event.target.value);
    if (startsWithNonNumeric(val)) {
      // 作业视频当输入框首个字母是英文的时候会实时显示在span上（08:05:00）
      setOutputValue(event.target.value);
    }
  };

  const handleNumButtonClick = () => {
    if (_.isEmpty(outputValue)) {
      setOutputValue(inputValue);
      return;
    }
    setOutputValue("");
  };

  useLayoutEffect(() => {
    if (spanRef.current) {
      // 获取span像素为了后期做像素长度判断（07:26:00）
      setSpanWidth(spanRef.current.offsetWidth);
    }
  }, [outputValue]);

  const getSpanBGC = (): string => {
    // 像素长度判断（07:26:00）
    return spanWidth > 40 ? "red" : "green";
  };

  /**
   * 点击颜色按钮会更改全局颜色
   */
  const butColorOnChick = () => {
    if (["blue", "red"].includes(inputValue)) {
      setColor(inputValue as "blue" | "red");
    }
  };

  return (
    <Fragment>
      <input
        type="text"
        value={inputValue}
        onChange={handleInputChange}
        style={{ marginRight: '5px' }}
      />
      <div>
        <button onClick={handleNumButtonClick}>btn数字</button>
        <button onClick={butColorOnChick}>btn颜色</button>
        <span ref={spanRef} style={{ backgroundColor: getSpanBGC(), marginRight: '5px' }}>
          {outputValue}
        </span>
      </div>
    </Fragment>
  );
};
